/*
 * Copyright (C) 2007 Evan Long    longx223 (at) umn (dot) edu
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

/**
 * @file   cvector.c
 * @author Evan Long
 * 
 * @brief  
 * 
 * 
 */

#include <string.h>
#include <stdlib.h>
#include "cvector.h"
#include "safe_malloc.h"

cvector_t* new_cvector(int element_size)
{
  cvector_t* tmp = (cvector_t*)safe_malloc(sizeof(cvector_t));
  tmp->size = 128;
  tmp->end_index = 0;
  tmp->element_size = element_size;
  tmp->data = (void*)safe_malloc(element_size * 128);

  return tmp;
}

void add_element(cvector_t* vec, void* element)
{
  void* loc = vec->end_index * vec->element_size + vec->data;
  memcpy(loc, element, vec->element_size);
  vec->end_index++;

  if(vec->size == vec->end_index)
  {
    int oldsize = vec->size;
    int newsize = oldsize * 2;
    void* newbuf = (void*)safe_malloc(vec->element_size * newsize);
    memcpy(newbuf, vec->data, vec->element_size * oldsize);
    free(vec->data);
    vec->data = newbuf;
    vec->size = newsize;
  }
}

void* element_at(cvector_t* vec, int idx)
{
  return (void*)(idx * vec->element_size + vec->data);
}

void free_vector(cvector_t* vec)
{
  free(vec->data);
  free(vec);
}
